from flask import Blueprint, redirect, url_for, request, render_template, current_app, flash
from flask_login import login_user, login_required, current_user, logout_user
from datetime import datetime
from app.models import Admin, Role
from app.constants import ADMIN_PAGE_LIMIT
from app.utils import create_nonce_str, create_password
from app.forms import AdminForm, EditPasswordForm, LoginForm
from app import db

admin_controller = Blueprint("admin", __name__, url_prefix="/admin/user")

@admin_controller.route("/index")
@login_required
def index():
    page = request.args.get('page', 1, type = int)
    keyword = request.args.get('keywords', '', type=str)
    try:
        pagination = Admin.query.filter(Admin.username.like('%'+keyword+'%')).paginate(page, per_page=ADMIN_PAGE_LIMIT)
    except Exception as e:
        current_app.logger.error(e)

    return render_template("admin/user/index.html", pagination=pagination)

@admin_controller.route('/add', methods=["GET", "POST"])
@login_required
def add():
    form = AdminForm()
    roles = Role.query.all()
    form.role_id.choices = [(c.id, c.name) for c in roles]
    form.role_id.choices.insert(0, (0, '请选择角色'))

    if request.method == "POST":
        if form.validate_on_submit():
            role_id = form.role_id.data
            username = form.username.data
            password = form.password.data
            status = request.form.get('status', 1, type=int)
            salt = create_nonce_str()
            pwd = create_password(password, salt)
            try:
                admin = Admin(role_id=role_id, username=username,password=pwd, salt=salt, status=status)
                db.session.add(admin)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("添加管理员失败")
            return redirect(url_for('admin.index'))
        
    return render_template("admin/user/add.html", form=form)

@admin_controller.route('/edit', methods=["GET", "POST"])
@login_required
def edit():
    id = request.args.get("id", 0, type=int)
    if id == 1:
        flash("超级管理员不能编辑")
        return redirect(url_for('admin.index'))
    try:
        admin = Admin.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("管理员不存在")
        return redirect(url_for('admin.index'))
    
    form = AdminForm(role_id=admin.role_id, username=admin.username)
    roles = Role.query.all()
    form.role_id.choices = [(c.id, c.name) for c in roles]
    form.role_id.choices.insert(0, (0, '请选择角色'))

    if request.method == "POST":
        if id == 1:
            flash('超级管理员不能修改')
            return redirect(url_for('.index'))
        if form.validate_on_submit():
            role_id = form.role_id.data
            username = form.username.data
            password = form.password.data
            status = request.form.get('status', 1,type=int)

            admin.role_id = role_id
            admin.username = username
            admin.status = status
            salt = create_nonce_str(6)
            pwd = create_password(password, salt)
            admin.salt = salt
            admin.passowrd = pwd
            try:
                db.session.add(admin)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("修改失败")
            return redirect(url_for(".index"))
        
    return render_template("admin/user/edit.html", form=form, admin=admin)

@admin_controller.route('/delete_op', methods=["GET"])
@login_required
def delete_op():
    id = request.args.get("id")
    id_list = id.split(',')
    if "1" in id_list:
        flash('超级管理员不能删除')
        return redirect(url_for('.index'))
    try:
        Admin.query.filter(Admin.id.in_(id_list)).delete(synchronize_session=False)
        # db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        flash("删除失败")
    return redirect(url_for(".index"))

@admin_controller.route("/status")
@login_required
def status():
    status = request.args.get('status', 1, type=int)
    id = request.args.get('id', '', type=str)
    if not id:
        flash('请选择管理员')
        return redirect(url_for('.index'))
    id_list = id.split(',')
    if "1" in id_list:
        flash('不能设置超级管理员')
        return redirect(url_for('.index'))
    try:
        Admin.query.filter(Admin.id.in_(id_list)).update({Admin.status: status}, synchronize_session=False)
    except Exception as e:
        current_app.logger.error(e)
        flash('修改失败')
    return redirect(url_for('.index'))

@admin_controller.route("/password", methods=["GET", "POST"])
@login_required
def password():
    form = EditPasswordForm()
    if request.method=='POST':
        if form.validate_on_submit():
            try:
                admin = Admin.queury.filter_by(id=current_user.id).first()
            except Exception as e:
                current_app.logger.error(e)
                flash("管理员不存在")
                return redirect(url_for('.index'))

            oldpassword = form.oldpassword.data
            password = form.oldpassword.data
             # 判断旧密码是否正确
            if create_password(oldpassword, admin.salt) != admin.password:
                flash("旧密码不正确")
                return redirect(url_for('.index'))
            
            salt = create_nonce_str()
            password = create_password(password, salt)
            admin.salt = salt
            admin.password = password
            try:
                db.session.add(admin)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("修改密码失败")
    return render_template('admin/user/password.html', form=form)

@admin_controller.route("/login", methods=["GET", "POST"])
def login():
    form = LoginForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            username = form.username.data
            password = form.password.data
            remember = request.form.get('remember', 0, type=int)
            try:
                admin = Admin.query.filter_by(username=username).first()
            except Exception as e:
                current_app.logger.error(e)
            if admin:
                if create_password(password, admin.salt) == admin.password:
                    login_user(admin, remember=remember)
                    # 修改登录次数与时间
                    admin.last_login_entered = admin.update_time
                    admin.update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    admin.login_ip = request.remote_addr
                    admin.times = admin.times + 1
                    db.session.add(admin)
                    db.session.commit()
                    return redirect(url_for('admin_index_controller.index'))
            flash("用户名或密码错误")

    return render_template('admin/login.html', form=form)

@admin_controller.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(url_for('admin.login'))